﻿using MediatR;
using Process.Api.Application.Command;
using Process.BLL;
using Process.DAL;
using Process.ErrorCod;
using Process.Infastructure;
using Process.Model;

namespace Process.Api.Application.Handler
{
    public class DeleteProcessTypeHandler : IRequestHandler<DeleteProcessTypeCommand, ApiResult<int>>
    {
        private readonly IProcessRepository<ProcessType> _processTypeRepository;
        private readonly ILogger<DeleteProcessTypeHandler> _logger;

        public DeleteProcessTypeHandler(IProcessRepository<ProcessType> processTypeRepository, ILogger<DeleteProcessTypeHandler> logger)
        {
            _processTypeRepository = processTypeRepository;
            _logger = logger;
        }
        /// <summary>
        /// 工序分类删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(DeleteProcessTypeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var query =_processTypeRepository.GetAllAsync().FirstOrDefault(x => x.Id == request.Id && !x.IsDelete);
            if (query != null)
            {
                query.IsDelete = true;
            }
            var res = _processTypeRepository.UpdateAsync(query).Result;
            if (res > 0)
            {
                _logger.LogInformation("删除工序分类数据成功");
                result.Code = ErrorStatus.Success;
                result.Message = "删除工序分类数据成功";
                result.Data = res;
            }
            else
            {
                _logger.LogError("删除工序分类数据失败");
                result.Code = ErrorStatus.Error;
                result.Message = "删除工序分类数据失败";
                result.Data = res;
            }
            return result;
        }
    }
}
